<template>
    <div class="container flex" >
        
        <div class="main">
            <n-card class="">
                <h1>{{curArticle.title}}</h1>
                <hr/>
                <img class="mt10" style="width: 100%;height: ;" :src="curArticle.main_img" alt="">
                <div v-html="curArticle.content"></div>
            </n-card>
            <n-card>
                <div class="flex j-a at-center">
                    <div class="my-hand" :style="likeStatus?`color:#FF6600;`:``" @click="changeLike()">{{likeStatus?'已点赞':'点赞'}}</div>
                    <div class="my-hand" :style="collectStatus?`color:#FF6600;`:``" @click="changeCollect()">{{collectStatus?'已收藏':'收藏'}}</div>
                </div>
            </n-card>
            <n-card class="mt10">
                <template #header>
                    <h3 style="border-bottom:2px solid #333">评论区</h3>
                    <n-input class="mt10" 
                    v-model:value="commentContent"
                    ref="commentContentRef"
                        placeholder="写下你的评论吧"
                        type="textarea" :autosize="{minRows: 3}"></n-input>
                        <div class="flex " style="justify-content: end;">
                            <myButton class="mt10" @click="createComment()">发表评论</myButton>
                        </div>
                    <h4 class="mt10">全部评论</h4>
                    <div class="comment flex" v-for="(item,index) in commentList" :key="index">
                        <img class="comment-img" :src="globalProperties.$imgServer+item.avatar" style="" alt="">
                        <div class="comment-main">
                            <div class="flex j-sb" style="width: 100%;">
                                <div style="flex:1" class="mr10">   
                                    <div class="name">{{item.from_user_name}} <svg-icon iconName="xingbienv"></svg-icon> </div>
                                    <div class="content">{{item.content}}</div>
                                    <div class="handle flex">
                                        <!-- <div class="handle-item mr10"><svg-icon className="comIconStyle" iconName="icon-dianzan"></svg-icon><span>40</span></div> -->
                                        <div class="handle-item mr10" @click="openReply(item.id)"><svg-icon className="comIconStyle" iconName="icon-act_huifuzixun"></svg-icon><span> {{item.replyList&& item.replyList.length }}</span></div>
                                        <div v-if="item.from_user_id == getItem('curUserInfo').id" class="handle-item mr10" @click="deleteComment(item.id)"><svg-icon className="comIconStyle" iconName="icon-delete"></svg-icon></div>
                                    </div>
                                    <div class="mt10 w100" v-show="replyFlag === item.id">
                                        <n-input type="textarea" :autosize="{minRows: 3}" :placeholder="`回复【${item.content&&item.content.length>6?item.content.substring(0,6)+'..':item.content}】`" v-model:value="replyContent" ></n-input>
                                        <div class="flex mt10" style="justify-content: end; ">
                                            <n-button style="margin-left: 5px;" size="small" @click="replay(item)">回复</n-button>
                                            <n-button style="margin-left: 5px;" size="small" @click="cancelReply()">取消</n-button>
                                        </div>
                                    </div>
                                </div>
                                <div style="font-size: 15px; color: #ccc;">
                                    {{item.create_time}}
                                </div>
                            </div>
                            <div class="reply-box">
                                <div class="comment flex" v-for="(replyitem,reindex) in item.replyList" :key="reindex">
                                    <img class="comment-img" :src="globalProperties.$imgServer+replyitem.avatar" style="width: 45px;height: 45px;" alt="">
                                    <div class="comment-main">
                                        <div class="flex j-sb" style="width: 100%; border-bottom: 1px solid #f2f2f2;">
                                            <div style="flex:1" class="mr10">   
                                                <div style="font-size: 14px;" class="name">【{{replyitem.from_user_name}}】回复【{{replyitem.to_user_name}}】 <svg-icon iconName="xingbienv"></svg-icon> </div>
                                                <div style="font-size: 14px;" class="content">{{ replyitem.content }}</div>
                                                <div style="font-size: 14px;" class="handle flex">
                                                    <!-- <div class="handle-item mr10"><svg-icon style="font-size: 12px;" className="comIconStyle" iconName="icon-dianzan"></svg-icon><span style="font-size: 12px;">40</span></div> -->
                                                    <div class="handle-item mr10" @click="openReply(replyitem.id)"><svg-icon style="font-size: 12px;" className="comIconStyle" iconName="icon-act_huifuzixun"></svg-icon><span style="font-size: 12px;">回复</span></div>
                                                    <div v-if="replyitem.from_user_id == getItem('curUserInfo').id" class="handle-item mr10" @click="deleteComment(replyitem.id)"><svg-icon className="comIconStyle"  iconName="icon-delete"></svg-icon></div>
                                                </div>
                                                <div class="mt10 w100" v-show="replyFlag === replyitem.id">
                                                    <n-input type="textarea" :autosize="{minRows: 3}"  :placeholder="`回复【${replyitem.content&&replyitem.content.length>6?replyitem.content.substring(0,6)+'..':replyitem.content}】`" v-model:value="replyContent" ></n-input>
                                                    <div class="flex mt10" style="justify-content: end;">
                                                        <n-button style="margin-left: 5px;" size="small" @click="replay(replyitem)">回复</n-button>
                                                        <n-button style="margin-left: 5px;" size="small" @click="cancelReply()">取消</n-button>
                                                    </div>
                                                </div>
                                            </div>
                                            <div style="font-size: 15px; color: #ccc;">
                                                {{replyitem.create_time}}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-if="commentList.length === 0" class="w100 flex" style="justify-content: center;position: relative;">
                        <h2 style="position: absolute;bottom:80px ;left: 50%;transform: translateX(-50%);">暂无评论</h2>
                        <img src="@/assets/img/noComment.png" alt="" style="width: 60%;">
                    </div>
                </template>
            </n-card>
        </div>
        <div class="side">
            <n-card>
                <div class="flex at-center">
                    <img :src="globalProperties.$imgServer+curArticle.authorAvatar" style="width: 60px; height: 60px; border-radius: 50%;border: 2px #000 solid;margin-right: 15px;" alt="">
                    <div class=" flex at-center"><h2>123</h2><svg-icon :iconName="curArticle.gender==1?`icon-xingbienan`:curArticle.gender==1?`icon-xingbienv`:''" className="sexIconStyle"></svg-icon></div>
                </div>
                <div class="mt10 flex j-sb">
                    <my-button :width="`48%`" class="mr10" @click="subscribe()" v-if="curArticle && curArticle.authorId !== getItem('curUserInfo').id">{{subscribeStatus}}</my-button>
                    <my-button :width="curArticle && curArticle.authorId !== getItem('curUserInfo').id?`48%`:`100%`"  class="" @click="tohomePage">{{curArticle && curArticle.authorId !== getItem('curUserInfo').id?`他`:`我`}}的主页</my-button>
                </div>
            </n-card>
            <n-card>
                <div class="flex j-a">
                    <div class="flex at-center" style="font-weight: 600; font-size: 16px;"><span class="mr10">点赞数</span>{{ curArticle.like_count }}</div>
                    <div class="flex at-center" style="font-weight: 600; font-size: 16px;"><span class="mr10">浏览数</span>{{ curArticle.view_count }}</div>
                </div>
            </n-card>
            <n-card title="相关标签">
                <my-tag class="mr10 mt10" v-for="(item,index) in curArticle.tagsName" :key="index"  :showColor="true">{{ item }}</my-tag>
            </n-card>
            <n-card class="" title="相关话题">
                <myTopicCard v-for="(item,index) in curArticle.topicName" :key="index">{{item}}</myTopicCard>
            </n-card>
            <n-card title="推荐文章" class="mt10">
            </n-card>
            <n-card class="">
                <div class="recommend" style="font-weight: 600;" v-for="(item,index) in recommendArticles" :key="index">{{ item.title }}</div>
            </n-card>
        </div>
    </div>
    <n-modal
      v-model:show="delReplyModal"
      preset="dialog"
      title="删除评论"
      content="确认删除?"
      positive-text="确认"
      negative-text="算了"
      @positive-click="submitDel"
      @negative-click="cancelDel"
    >
    </n-modal>
</template>

<script lang="ts" setup>
import router from '@/router';
import { useRoute } from 'vue-router';
import requestList from '@/service/request';
import { onMounted, ref,getCurrentInstance } from 'vue';
import { create } from 'lodash';
import { getItem } from '@/utils/local';
const route = useRoute()
const { appContext : { config: { globalProperties } } } = (getCurrentInstance() as any)
//标签列表
const tagsList =ref<any[]>([])
const getTags = async () =>{
    const res = await requestList.tagListApi({all:true})
    if(res.code === 1){
        tagsList.value = res.data as any
    }
}
//话题列表
const topicList = ref<any[]>([])
const getTopic = async ()=>{
    const res = await requestList.topicListApi({all:true})
    if(res.code === 1){
        topicList.value = res.data as any
    }
}

const curArticle = ref<any>({})
const getCurArticle = async () => {
    const res = await requestList.getArticleByIdApi({id:Number(route.query.id)})
    if(res.code === 1){
        console.log(topicList.value);
        
            let tagsName:string[] = []
            let topicName:string[] = []
            let tagIds = (res.data as any).tags.split(',')
            let topicIds = (res.data as any).topic.split(',')
            tagsList.value.forEach((x:any)=>{
                tagIds.forEach((y:any)=>{
                    if(x.id === Number(y)){
                        tagsName.push(x.tag_name)
                    }
                })
            })
            topicList.value.forEach((x:any)=>{
                topicIds.forEach((y:any)=>{
                    if(x.id === Number(y)){
                        topicName.push(x.topic_name)
                    }
                })
            });
            (res.data as any).tagsName = tagsName;
            (res.data as any).topicName = topicName
            curArticle.value = (res.data as any)
    }
}

const recommendArticles = ref<any[]>([])
const getReCommentArticle = async () =>{
    const postData = {
        tagIds: curArticle.value.tags.split(','),
        curArticleId:route.query.id
    }
    const res = await requestList.getReCommentArticleApi(postData)
    if(res.code === 1){
        recommendArticles.value = (res.data as any).slice(0,6)
    }
}

const users = ref<any[]>([])
const getUsers = async ()=>{
    const res = await requestList.userListApi({all:true})
    if(res.code === 1){
        users.value = (res.data as any)
    }
}

const commentList = ref<any[]>([])
const getCommentList = async ()=>{
    const res = await requestList.getCommentByArticleApi({articleId:Number(route.query.id)})
    if(res.code === 1){
        commentList.value = (res.data as any)
        commentList.value.forEach((item:any)=>{
            users.value.forEach((data:any)=>{
                if(item.from_user_id === data.id){
                    item.from_user_name = data.username
                    item.avatar = data.avatar
                }
            })
        })
        commentList.value.forEach(async (item:any)=>{
            const res =  await requestList.getReplyByCommentApi({commentId:item.id})
            if(res.code === 1 ){
                item.replyList = res.data as any
                item.replyList.forEach((replyItem:any)=>{
                users.value.forEach((data:any)=>{
                    if(replyItem.from_user_id === data.id){
                        replyItem.from_user_name = data.username
                        replyItem.avatar = data.avatar
                    }
                    if(replyItem.to_user_id === data.id){
                        replyItem.to_user_name = data.username
                    }
                })
            })
            }
        })
        console.log(commentList.value);
    }
}

const commentContent = ref('')
const commentContentRef = ref(null)
const createComment = async () =>{  
    if(commentContent.value.trim() == ''){
        window.$message.warning('评论不能为空！');
       (commentContentRef.value as any).focus()
        return
    }
    const postData = {
        parent_id:0,
        content:commentContent.value,
        from_user_id:getItem('curUserInfo').id,
        to_user_id:curArticle.value.authorId,
        article_id:Number(route.query.id)
    }
    const res = await requestList.createCommentApi(postData)
    if(res.code === 1){
        window.$message.success('评论成功！')
        getCommentList()
        commentContent.value = ''
    }
}

const cancelReply = () =>{
    replyContent.value = ''
    replyFlag.value = 0    
}

const replyFlag = ref(0)
const replyContent = ref('')
const openReply = (id:number) => {
    replyFlag.value = id    
}
const replay = async (item:any) => {
    if(replyContent.value.trim() == ''){
        window.$message.warning('回复内容不能为空！');
        return
    }

    const {to_user_id,parent_id,id,from_user_id} = item
    console.log(item);
    const postData = {
        parent_id:parent_id?parent_id:id,
        content:replyContent.value,
        from_user_id:getItem('curUserInfo').id,
        to_user_id:from_user_id,
        article_id:0
    }
    const res = await requestList.createCommentApi(postData)
    if(res.code === 1){
        window.$message.success('回复成功！')
        getCommentList()
        cancelReply()
    }
}

const delReplyModal = ref(false)
const delReplyModalId = ref(0)
const  deleteComment = async (id:number)=>{
    delReplyModal.value = true
    delReplyModalId.value = id
}

const cancelDel = ()=>{
    delReplyModal.value = false
    delReplyModalId.value = 0
}
const submitDel = async ()=>{
    const res = await requestList.deleteCommentApi({id:delReplyModalId.value})
    if(res.code === 1){
        window.$message.success('删除成功！')
        getCommentList()
        cancelDel()
    }
}

const guanzhuList = ref<any[]>([]) // 关注列表
const fensiList = ref<any[]>([]) // 粉丝列表
const subscribeStatus = ref('') //关注状态

const getGuanzhuList = async () => {
    const postData = {
        type:1,
        all:true,
        user_id:curArticle.value.authorId
    }
    const res = await requestList.subscribeByUserApi(postData)
    if(res.code === 1){
        guanzhuList.value = res.data as any
    }
}
const getFensiList = async () => {
    const postData = {
        type:2,
        all:true,
        user_id:curArticle.value.authorId
    }
    const res = await requestList.subscribeByUserApi(postData)
    if(res.code === 1){
        fensiList.value = res.data as any
        const guanzhuIds = guanzhuList.value.map((item:any)=>item.id)
        const fensiIds = fensiList.value.map((item:any)=>item.id)
        const curUserId = getItem('curUserInfo').id
        if(guanzhuIds.includes(curUserId)&& !fensiIds.includes(curUserId)){
            subscribeStatus.value = '回关' 
        }else if(!guanzhuIds.includes(curUserId)&& fensiIds.includes(curUserId)){
            subscribeStatus.value = '已关注' 
        }else if(guanzhuIds.includes(curUserId)&& fensiIds.includes(curUserId)){
            subscribeStatus.value = '已互关' 
        }else if(!guanzhuIds.includes(curUserId)&& !fensiIds.includes(curUserId)){
            subscribeStatus.value = '去关注' 
        }
    }
}

const subscribe = async () =>{
    const status:number = ['回关','去关注'].includes(subscribeStatus.value)? 1:0;
    const postData = {
        be_subscribe_id:curArticle.value.authorId,
        subscribe_id:getItem('curUserInfo').id,
        status,
    }
    
    const res = await requestList.changeSubscribeStatusApi(postData)
    if(res.code === 1){
        const msg:string = status?'已关注':'已取消关注'
        window.$message.success(msg)
        setTimeout(async ()=>{
            await getGuanzhuList()
            await getFensiList()
        },300)
        
    }
}

const tohomePage = () =>{
    router.push({
        path:'/homePage',
        query:{id:curArticle.value.authorId}
    })
}

// 点赞
const likeStatus = ref(false)
const likeArticle = ref<any[]>([])
const likeArticleByUser = async () => {
    const res = await requestList.likeArticleListByUserApi({user_id:getItem('curUserInfo').id})
    if(res.code === 1){
        likeArticle.value = res.data as any
        console.log(likeArticle.value);
        
        if(likeArticle.value.map((item:any)=>(item.article_id)).includes(curArticle.value.id)){
            likeStatus.value = true
        }else{
            likeStatus.value = false
        }
    }
}
const changeLike = async ()=>{
    const postData = {
         user_id:getItem('curUserInfo').id,
         article_id:curArticle.value.id,
         status:likeStatus.value?0:1
    }
    const res = await requestList.changeLikeArticleStatusApi(postData)
    if(res.code === 1){
        setTimeout(()=>{
            likeArticleByUser()
        },300)
    }
}

// 收藏
const collectStatus = ref(false)
const collectArticle = ref<any[]>([])
const collectArticleByUser = async () => {
    const res = await requestList.collectListByUserApi({user_id:getItem('curUserInfo').id})
    if(res.code === 1){
        collectArticle.value = res.data as any
        if(collectArticle.value.map((item:any)=>(item.article_id)).includes(curArticle.value.id)){
            collectStatus.value = true
        }else{
            collectStatus.value = false
        }
    }
}
const changeCollect = async ()=>{
    const postData = {
         user_id:getItem('curUserInfo').id,
         article_id:curArticle.value.id,
         status:collectStatus.value?0:1
    }
    const res = await requestList.changeCollectStatusApi(postData)
    if(res.code === 1){
        setTimeout(()=>{
            collectArticleByUser()
        },300)
    }
}

onMounted(async ()=>{
    await getTags()
    await getTopic()
    await getCurArticle()
    await getReCommentArticle()
    await getUsers()
    await getCommentList()
    await getGuanzhuList()
    await getFensiList()
    await likeArticleByUser()
    await collectArticleByUser()
})



</script>

<style lang="scss" scoped>
hr{
    border: #000 1px solid;
}
.main{
    flex: 1;
    .comment{
        margin-top: 10px;
        &-img{
            width: 60px; height: 60px; border-radius: 50%;border: 2px #000 solid;margin: 0 15px;
        }
        &-main{
            flex: 1;
            padding: 4px;
            .name{
                font-weight: 600;
            }
            .content{
                font-size: 15px;
            }
            .handle{
                margin-top: 8px;
                &-item{
                    cursor: pointer;
                    font-size: 14px;
                    &:hover{
                    }
                }
                
            }
            .reply-box{
                padding: 5px;
                margin: 10px 0;
                border-radius: 10px;
            }
        }
       
    }
}
.side{
    margin-left: 10px;
    width: 300px;
    .recommend{
        padding: 10px ;
        transition: all .4s;
        cursor: pointer;
        &:hover{
            background: $color3;
            border-radius: 8px;
            transform: scale(1.1);
        }
    }
}
.sexIconStyle{
    font-size: 28px;
}
.comIconStyle{
    margin-right: 5px;
}

.my-hand{
    font-size: 18px;font-weight: 600;cursor: pointer;transition: all .3s;
    width: 50%;
    text-align: center;
    &:hover{
        transform: scale(1.5);
    }
}

</style>